<script setup>
const IOServiceUUIDS = {
  SERVICE: '64A70012-F691-4B93-A6F4-0968F5B648F8'.toLowerCase(),
  BATTERY_CHAR: '64A70007-F691-4B93-A6F4-0968F5B648F8'.toLowerCase(),
  USER_BUTTON_CHAR: '64A7000D-F691-4B93-A6F4-0968F5B648F8'.toLowerCase(),
  VIBRATOR_CHAR: '64A70008-F691-4B93-A6F4-0968F5B648F8'.toLowerCase(),
  LED_CHAR: '64A70009-F691-4B93-A6F4-0968F5B648F8'.toLowerCase(),
  KEEP_ALIVE_CHAR: '64A7000F-F691-4B93-A6F4-0968F5B648F8'.toLowerCase(),
}

const SensorServiceUUIDS = {
  SERVICE: '64A70011-F691-4B93-A6F4-0968F5B648F8'.toLowerCase(),
  TEMP_CHAR: '64A70014-F691-4B93-A6F4-0968F5B648F8'.toLowerCase(),
  QUATERNIONS_CHAR: '64A70002-F691-4B93-A6F4-0968F5B648F8'.toLowerCase()
}

const options = {
  filters: [
    { name: 'Kano-wand' },
    { namePrefix: 'Kano' }
  ],
  optionalServices: [IOServiceUUIDS.SERVICE, SensorServiceUUIDS.SERVICE]
}

let device = null;
let server = null;

const position = {
  x: 0,
  y: 0,
  w: 0,
  z: 0
};

let timer = null;

  async function connect() {
    device = await navigator.bluetooth.requestDevice(options);

    server = await device.gatt.connect();

    console.log(device.gatt.connected);
  }


  async function disconnect() {
    if(device && device.gatt) {
      await device.gatt.disconnect();
      console.log('disconnect');
    }
  }

  async function getButton() {
    // --------
    const IOService = await server.getPrimaryService(IOServiceUUIDS.SERVICE);
    console.log(IOService)
    const Button_CHAR = await IOService.getCharacteristic(IOServiceUUIDS.USER_BUTTON_CHAR);
    console.log(Button_CHAR)
    const btn = await Button_CHAR.readValue();
    if(btn) {
      const v = btn.getUint8(0);
      console.log(v);
    }
  }

  async function getPosition() {
    const SensorService = await server.getPrimaryService(SensorServiceUUIDS.SERVICE);
    const POSITION_CHAR = await SensorService.getCharacteristic(SensorServiceUUIDS.QUATERNIONS_CHAR);
    await POSITION_CHAR.startNotifications();
    POSITION_CHAR.addEventListener('characteristicvaluechanged', (e) => {
      let value = e.target.value;
      position.y = value.getUint16(0, true);
      position.x = value.getUint16(2, true);
      position.w = value.getUint16(4, true);
      position.z = value.getUint16(6, true);
    });

    timer = setInterval(() => {
      console.log(position)
    }, 300);
  }

async function stopGetPosition() {
  const SensorService = await server.getPrimaryService(SensorServiceUUIDS.SERVICE);
  const POSITION_CHAR = await SensorService.getCharacteristic(SensorServiceUUIDS.QUATERNIONS_CHAR);
  await POSITION_CHAR.stopNotifications();
  clearTimeout(timer);
}
</script>

<template>
  <div>
    <button @click="connect">connect</button>
    <button @click="getButton">button status</button>
    <button @click="getPosition">position status</button>
    <button @click="stopGetPosition">stop position status</button>
    <button @click="disconnect">disconnect</button>
  </div>
</template>

<style scoped>

</style>
